package handle

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

// Token 结构体定义
//type Token struct {
//	AccessToken string `json:"access_token"`
//	Scope       string `json:"scope"`
//	TokenName   string `json:"token_type"`
//	ExpiresIn   string `json:"expires_in"`
//}

func GetAccessToken(grantType, clientID, clientSecret string) (*Token, error) {
	url := "http://dev.meirenji.cn/oauth/token"

	payload := fmt.Sprintf("grant_type=%s&client_id=%s&client_secret=%s", grantType, clientID, clientSecret)
	req, err := http.NewRequest("POST", url, bytes.NewBufferString(payload))
	if err != nil {
		return &Token{}, err
	}

	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return &Token{}, err
	}
	defer func(Body io.ReadCloser) {
		err := Body.Close()
		if err != nil {
			panic(err)
		}
	}(resp.Body)

	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return &Token{}, err
	}

	var result Token
	err = json.Unmarshal(body, &result)
	if err != nil {
		return &Token{}, err
	}

	return &result, nil
}
